package ups.glre.news.jms;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.ejb.Local;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.Topic;


@Local
@Stateless
public class NewsJmsServiceBean implements NewsJmsService {

    private static final Logger log = Logger.getLogger(NewsJmsServiceBean.class.getName());

    @Resource
    private SessionContext sessionContext;

    @Resource(mappedName="topic/newsTopic")
    private Topic destination;

    @Resource(mappedName="ConnectionFactory")
    private ConnectionFactory connectionFactory;

	@Override
	public void sendMessage(String category, String title, String author,
			String content, String date) {
		Connection connection = null;
        try {
            connection = connectionFactory.createConnection();
            Session session = connection.createSession(false,
                    Session.AUTO_ACKNOWLEDGE);

            Message message = session.createTextMessage();
            fillMessage(message, category, title, author, content, date);
            MessageProducer producer = session.createProducer(destination);
            producer.send(message);
            log.info("Message sent");

        } catch (Exception e) {
            log.log(Level.SEVERE, "Error sending message", e);
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception ex) {
                log.log(Level.WARNING, "Problem closing JMS Connection", ex);
            }
        }
	}
	
	private void fillMessage(Message msg ,String category, String title, String author,
			String content, String date) throws JMSException {
		msg.setStringProperty(Constants.NEWS_AUTHOR_PROPERTY_NAME, author);
    	msg.setStringProperty(Constants.NEWS_CATEGORY_PROPERTY_NAME, category);
    	msg.setStringProperty(Constants.NEWS_CONTENT_PROPERTY_NAME, content);
    	msg.setStringProperty(Constants.NEWS_DATE_PROPERTY_NAME, date);
    	msg.setStringProperty(Constants.NEWS_TITLE_PROPERTY_NAME, title);
	}

}
